import turtle
import os
import tkinter
import random
import math
import re

def getXYpos():
    x = turtle.xcor()
    y = turtle.ycor()
    return x, y

keyword = {
    # 1. 优先定义全角符号转半角（放在最前面，保证优先匹配）
    "：": ":",
    "；": ";",
    "！": "!",
    "？": "?",
    "（": "(",
    "）": ")",
    "【": "[",
    "】": "]",
    "，": ",",
    "。": ".",
    "’": "'",
    "‘": "'",
    '“': '"',
    '”': '"',
    "　": " ",  # 全角空格（补充）
    # 原有关键词保持不变...
    "导入": "import",
    "从": "from",
    "以": "with",
    "打开": "open",
    "全部": "*",
    "乌龟模块": "turtle",
    "输出": "print",
    "输入": "input",
    "循环": "while",
    "结束": "break",
    "不等于": "!=",
    "等于": "==",
    "和": "and",
    "或": "or",
    "叫": "as",
    "如果否则": "elif",
    "如果": "if",
    "否则": "else",
    "定义": "def",
    "小于": "<",
    "大于": ">",
    "小于等于": "<=",
    "大于等于": ">=",
    "遍历": "for",
    "在": "in",
    "是": "is",
    "赋值": "=",
    "检查": "try",
    "有错误？": "except",
    "字符串值": "ord",
    "迭代": "range",
    "增加": "append",
    "解包": "*",
    "类": "class",
    "注释": "#",
    "行定义": "lambda",
    "全局变量": "global",
    # turtle相关
    "左转": "left",
    "直行": "forward",
    "右转": "right",
    "后退": "backward",
    "到": "goto",
    "好": "done",
    "隐身": "hideturtle",
    "现身": "showturtle",
    "开始填充": "begin_fill",
    "结束填充": "end_fill",
    "笔的颜色": "color",
    "背景的颜色": "bgcolor",
    "填充的颜色": "fillcolor",
    "清屏": "clear",
    "图章": "shape",
    "拜拜": "bye",
    "抬笔": "penup",
    "落笔": "pendown",
    "面向": "setheading",
    "距离": "distance",
    "回到起点": "home",
    "画圆": "circle",
    "按下": "onkey",
    "速度": "speed",
    "标题": "title",
    "画布的高": "window_heihght",
    "画布的宽": "window_width",
    "当前角度": "heading",
    "当前位置": "getXYpos",
    # 快捷
    "死循环": "while True",
    "打开文件": "with open",
    # 错误
    "值错误": "ValueError",
    "类型错误": "TypeError",
    "语法错误": "SyntaxError",
    # tkinter相关
    "界面模块": "tkinter",
    "创建窗口": "Tk",
    "标签": "Label",
    "按钮": "Button",
    "输入框": "Entry",
    "文本框": "Text",
    "框架": "Frame",
    "网格布局": "grid",
    "包布局": "pack",
    "放置布局": "place",
    "尺寸": "geometry",
    "运行": "mainloop",
    "点击事件": "command",
    "获取内容": "get",
    "设置内容": "insert",
    "删除内容": "delete",
    "背景色": "bg",
    "前景色": "fg",
    "字体": "font",
    "宽度": "width",
    "高度": "height",
    "对齐": "justify",
    "粘性": "sticky",
    "行": "row",
    "列": "column",
    "列跨度": "columnspan",
    "行跨度": "rowspan",
    "内边距": "padx",
    "外边距": "pady",
    "禁用": "state='disabled'",
    "启用": "state='normal'",
    # random模块
    "随机模块": "random",
    "随机整数": "randint",
    "随机选择": "choice",
    "随机样本": "sample",
    "随机浮点数": "random",
    "打乱顺序": "shuffle",
    "随机范围": "randrange",
    "随机均匀分布": "uniform",
    # math模块
    "数学模块": "math",
    "圆周率": "pi",
    "自然常数": "e",
    "向下取整": "floor",
    "向上取整": "ceil",
    "四舍五入": "round",
    "根号": "sqrt",
    "正弦": "sin",
    "余弦": "cos",
    "正切": "tan",
    "反正弦": "asin",
    "反余弦": "acos",
    "反正切": "atan",
    "弧度转角度": "degrees",
    "角度转弧度": "radians",
    "自然对数": "log",
    "以10为底的对数": "log10",
    "幂运算": "pow",
    "双曲正弦": "sinh",
    "双曲余弦": "cosh",
    "双曲正切": "tanh",
    # 数学基础
    "乘": "*",
    "除": "/",
    "加": "+",
    "减": "-",
    "次方": "**",
    "根号": "sqrt",
    "相加": "sum",
    "最小值": "min",
    "最大值": "max",
    "排序": "sorted",
    "绝对值": "abs",
    "整数": "int",
    "字符串": "str",
    "浮点数": "float",
    "列表": "list",
    "字典": "dict",
    # time模块
    "时间模块": "time",
    "睡眠": "sleep",
    "获取时间戳": "time",
    "本地时间": "localtime",
    "格式化时间": "strftime",
    "暂停": "sleep",
    "时间结构": "struct_time",
    "时钟": "perf_counter",
    # datetime模块
    "日期时间模块": "datetime",
    "日期时间": "datetime",
    "日期": "date",
    "时间": "time",
    "时间差": "timedelta",
    "获取当前日期时间": "datetime.now",
    "获取当前日期": "date.today",
    "字符串转日期时间": "datetime.strptime",
    "日期时间转字符串": "strftime",
    "年": "year",
    "月": "month",
    "日": "day",
    "时": "hour",
    "分": "minute",  # 问题关键词：单个汉字「分」映射到minute
    "秒": "second",
    "毫秒": "microsecond",
    "星期": "weekday",
    "iso星期": "isoweekday",
    "添加时间": "timedelta",
}

# 排序时保持全角符号优先（长度相同的情况下，全角符号在前）
keywords_sorted = sorted(keyword.keys(), key=lambda x: (-len(x), x))

# 关键修复：正则模式优化，只匹配「独立出现」的关键词（前后不是中文、字母、数字、下划线）
# 排除字符集：中文字符(\u4e00-\u9fff)、字母(a-zA-Z)、数字(0-9)、下划线(_)
pattern = re.compile(
    rf"(?![\u4e00-\u9fff_a-zA-Z0-9])({'|'.join(re.escape(k) for k in keywords_sorted)})(?![\u4e00-\u9fff_a-zA-Z0-9])",
    re.UNICODE
)

def replace_outside_quotes(match):
    word = match.group(0)
    return keyword.get(word, word)

def full_to_half(text):
    """增强版全角转半角（确保所有符号都被处理）"""
    result = []
    for char in text:
        code = ord(char)
        if code == 12288:  # 全角空格
            result.append(' ')
        elif 65281 <= code <= 65374:  # 全角ASCII字符
            result.append(chr(code - 65248))
        elif code == 8220:  # 左双引号“
            result.append('"')
        elif code == 8221:  # 右双引号”
            result.append('"')
        elif code == 8216:  # 左单引号‘
            result.append("'")
        elif code == 8217:  # 右单引号’
            result.append("'")
        elif code == 8230:  # 省略号…
            result.append("...")
        else:
            result.append(char)
    return ''.join(result)

while True:
    file = input('请输入文件名：')
    if file == 'exit':
        exit()
    elif not os.path.exists(file):
        print(f"错误：文件'{file}'不存在")
    else:
        with open(file, 'r', encoding="utf-8") as f:
            code = f.read()
            code = full_to_half(code)  # 先执行全角转半角
        print("原始代码：")
        print(code)
        ok = input('这是你要执行的代码吗？(y/n)')
        if ok.lower() == 'y':
            # 优化正则替换逻辑：只处理引号外的部分，且不匹配变量名中的中文
            def process_non_quote(m):
                non_quote_part = m.group(0)
                return pattern.sub(replace_outside_quotes, non_quote_part)
            
            # 先匹配所有引号内的内容，只处理引号外的部分
            code_processed = re.sub(
                r"'[^'\\]*(?:\\.[^'\\]*)*'|\"[^\"\\]*(?:\\.[^\"\\]*)*\"|([^'\"]+)",
                lambda m: m.group(0) if m.group(1) is None else process_non_quote(m),
                code
            )

            print("\n转换后代码：")
            print(code_processed)
            
            try:
                exec(code_processed)
            except Exception as e:
                print(f"执行错误：{e}")